<?php
namespace Modules\Activity\Http\Controllers\Client\EggLottery;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

use \Modules\Activity\Entities\EggLottery\Activity;
use \Modules\Activity\Entities\ActivityOrder as Order;

use Validator;
use ThrowException;
use Auth;
use DB;
use Cache;


// 福袋订单
class OrderController extends Controller
{
    // 创建订单
    public function preview(Request $req) 
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        // $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');


        // 扭蛋机
        $activity = Activity::getEntity([
            'id' => $req->activity_id
        ]);

        // 购买总数
        $total = $req->total;

        // 检查是否超出限售
        $activity->checkSkuStock($total) || ThrowException::Conflict('库存不足~');

        // 检查是否超出限售
        $activity->checkSaleLimit($total);

        // 检查次数限制
        $activity->checkPerUserLimit($user, $total);

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
        ]);

        // 返回订单内容
        return $order->generatePreviewResponse($user);

        // 计算可用优惠券
        // $coupons = $order->filterCoupons($user->coupons()->with('base_coupon')->valid()->get());
        
        // $orderInfo = [
        //     'redpack' => $order->calcUsableRedpack($user),
        //     'is_use_redpack' => $isUseRedpack,
        //     'coupons' => $coupons,
        //     'carriage' => $order->carriage,
        //     'coupon_discount' => $order->coupon_discount,
        //     'product_money_price' => $order->product_money_price,
        //     'product_score_price' => $order->product_score_price,
        //     'pay_money_price' => $order->pay_money_price,
        //     'pay_score_price' => $order->pay_score_price,
        // ];

        // return [
        //     'order' => $orderInfo
        // ];
    }

    // 创建订单
    public function confirm(Request $req) 
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();
        // 1秒内只能调1次此api
        Auth::limitTimeBeforeProcess($user, 'create_order', 1);

        // $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        // 扭蛋机
        $activity = Activity::getEntity([
            'id' => $req->activity_id
            
        ]);

        // 购买总数
        $total = $req->total;

        // 检查是否超出限售
        $activity->checkSkuStock($total) || ThrowException::Conflict('库存不足~');

        // 检查次数限制
        $activity->checkPerUserLimit($user, $total);

        $skuableMaps = [
            [
                'skuable' => $activity,
                'total' => $total
            ]
        ];

        DB::beginTransaction();

        $coupon = NULL;
        if ($req->input('coupon_id'))
            $coupon = $user->coupons()->valid()->where('id', $req->coupon_id)->first();

        $isUseRedpack = $req->input('is_use_redpack');
        $isUseScore = $req->input('is_use_score');
        
        $order = Order::initWith($skuableMaps, $user, NULL, [
            'node' => $activity,
            'coupon' => $coupon,
            'is_use_redpack' => $isUseRedpack,
            'is_use_score' => $isUseScore,
            'is_visible' => 0,
        ]);

        $order->createAll();

        DB::commit();

        // 返回订单内容
        return $order->generateResponse();
    }

    // 试一试
    public function try(Request $req) 
    {
        $rule = [
            'activity_id' => ['required'],
            'total' =>  ['required']
        ];
        Validator::make($req->all(), $rule)->fails() && ThrowException::BadRequest(); 

        $user = Auth::requireLoginUser();

        // $cached = Cache::get($req->page_uuid) ?: ThrowException::Conflict('页面已失效，请刷新后重试~');

        // 福袋
        $activity = Activity::getEntity([
            'id' => $req->activity_id
        ]);

        // 购买总数
        $total = $req->total;

        // 仅仅
        DB::beginTransaction();

        // 取出sku
        $skuMaps = $activity->pickLuckySkusForTry($total, $user, null);

        $list = [];

        // 此处不要提交到数据库保存
        foreach ($skuMaps as $skuMap) {
            $sku = $skuMap['skuable'];
            array_push($list, [
                "title" => $sku->title,
                "number" => $sku->number,
                "thumb" => $sku->thumb,
                "money_price" => $sku->money_price,       // 价值 (人民币)
                "total" => $skuMap['total'],                 // 中奖数量
            ]);
        }

        $uuid = 'try_' . uniqid();

        $cached = [
            'sku_type' => 'egg_lottery_sku',
            'sku_id' => $skuMaps[0]['skuable']->id,
            'skus' => $list
        ];
        Cache::put($uuid, $cached, 1800);

        return [
            'package_uuid' => $uuid,
            // 'skus' => $list
        ];

    }
}
